    //
    //  FZHomeViewModel.m
    //  EnglishTalk
    //
    //  Created by CyonLeuPro on 15/6/26.
    //  Copyright (c) 2015年 Feizhu Tech. All rights reserved.
    //

#import "FZHomeViewModel.h"

#import "SRCommonConstants.h"
#import "FZHomeConstants.h"
#import "FZHomeBaseCollectionViewCell.h"
#import "FZHomeCollectionViewSectionFooterView.h"
#import "FZStyleSheet.h"
#import "UIImageView+FZDefaultPlaceholder.h"
#import "SRCommonWebViewController.h"

#import "FZHomeBannerCollectionViewCell.h"
#import "FZHomeHotVideoSectionFooterView.h"
#import "FZHomeAlbumCollectionViewCell.h"
#import "SRHomeFeatureCollectionViewCell.h"

#import <SRNetWorkManager.h>
#import "FZHomeSectionModel.h"
#import "FZHomeCourseModel.h"
//#import "FZHomeSliderModel.h"
#import "FZAdvertisementModel.h"
#import <MTLJSONAdapter.h>
#import "SRLoginManager.h"
#import "FZMCCacheManager.h"

#import "SRHomePageViewController.h"
#import "SRGradeListViewController.h"
#import "SRLearnAlbumViewController.h"
#import "UIAlertView+SRBlocks.h"
#import "SRMyBookListViewController.h"
#import "SRBookUnitSelectListViewController.h"

#define kHomeSectionHeaderHeight 65
#define kHomeSectionFooterHeight 45

#define kHomeCellIdentifierKey @"identifier"
#define kHomeCellSizeKey @"size"


@interface FZHomeViewModel ()<FZHomeAlbumCollectionViewCellDelegate>


@property (assign, nonatomic) UICollectionView *collectionView;
@property (assign, nonatomic) CGSize itemSize;
@property (strong, nonatomic) FZHomeCourseModel *addCourseModel;
@property (strong, nonatomic) FZHomeCollectionViewSectionHeaderView *bookHeaderView;

@property (strong, nonatomic) NSIndexPath *deleteIndexPath;

@end


@implementation FZHomeViewModel


- (instancetype)initWithCollectionView:(UICollectionView *)collectionView info:(FZHomeRootModel *)rootModel delegate:(id<FZHomeViewModelDelegate>)delegate {
    if (self = [super init]) {
        self.delegate = delegate;
        self.collectionView = collectionView;
        if (rootModel && rootModel.sectionModels) {
            self.sectionModels = (NSMutableArray *)rootModel.sectionModels;
        }
        
        CGFloat cellWidth = floorf((SCREEN_WIDTH - kFZHomeCollectionViewEdgeSpace * 3) / 2.f) - 1;
        CGFloat cellHeight = cellWidth * 119.0/165.0;
        
        
//        FZHomeCourseModel *addModel = [[FZHomeCourseModel alloc] init];
//        addModel.title = @"添加";
//        addModel.identifier = kHomeAddAlbumID;
//        self.addCourseModel = addModel;
//        self.isEditing = NO;
        
        self.itemSize = CGSizeMake(cellWidth, cellHeight);
        
    }
    
    return self;
}

- (void)reloadCurrentBook {
    NSString *bookID = [[NSUserDefaults standardUserDefaults] objectForKey:SRUserCurrentBookID];
    NSArray *books = [FZMCCacheManager defaultManager].books;
    if (bookID) {
        
        FZHomeCourseModel *destBook = nil;
        for (int i = 0; i < [books count]; ++i) {
            FZHomeCourseModel *item = books[i];
            NSString *itemID = [NSString stringWithFormat:@"%@", item.identifier];
            if ([bookID isEqualToString:itemID]) {
                destBook = item;
                break;
            }
        }
        
        if (destBook) {
            self.bookModel = destBook;
        }
        else  if ([books count] > 0) {
            self.bookModel = [books lastObject];
        }
        
    } else {
        
        if ([books count] > 0) {
            self.bookModel = [books lastObject];
        }
    }
}


- (void)cleanAllData {
    [self.sectionModels removeAllObjects];
}

- (NSInteger)numberOfSections {
    return self.sectionModels.count;
}

- (NSInteger)numberOfItemsInSection:(NSInteger)section {
    
    if (section >= 0 && section < self.sectionModels.count) {
        NSArray *items = [self itemsForSection:section];
        FZHomeSectionModel *sectionModel = self.sectionModels[section];
        if ([sectionModel.module isEqualToString:kHomeModuleAlbum]) {
            if (!self.isEditing) {
                return [items count] + 1;
            }
        }
        return [items count];
    }
    
    return 0;
}

- (id)itemForIndexPath:(NSIndexPath *)indexPath {
    NSArray *items = [self itemsForSection:indexPath.section];
    if (items && items.count > 0 && indexPath.item < items.count) {
        
        FZHomeSectionModel *sectionModel = self.sectionModels[indexPath.section];
        if ([sectionModel.module isEqualToString:kHomeModuleAlbum]) {
            
            NSArray *books = [FZMCCacheManager defaultManager].books;
            if (indexPath.item == [books count]) {
                return self.addCourseModel;
            } else if (indexPath.item >= 0 && indexPath.item < [books count] ) {
                return books[indexPath.item];
            } else {
                return nil;
            }
        }
        
        return items[indexPath.item];
    }
    return nil;
}

- (void)didSelectItemForIndexPath:(NSIndexPath *)indexPath {
    FZHomeSectionModel *sectionModel = self.sectionModels[indexPath.section];
    if ([sectionModel.module isEqualToString:kHomeModuleAlbum]) {
        NSArray *books = [FZMCCacheManager defaultManager].books;
        if (indexPath.item == [books count]) {
                //添加课本按钮
            [self onAddAlbumButton];
        } else {
            FZHomeCourseModel *item = [self itemForIndexPath:indexPath];
                //显示课程学习
            [self showAlbumDetailVC:item];
        }
    }
    else if ([sectionModel.module isEqualToString:kHomeModuleFeatures]) {
        FZHomeCourseModel *item = [self itemForIndexPath:indexPath];
//        NSArray *books = [FZMCCacheManager defaultManager].books;
//        FZHomeCourseModel *book = [books lastObject];
        FZHomeCourseModel *book = self.bookModel;
        if (!book) {
            
            [self.delegate homeViewModel:self showMessage:@"请先添加课本"];
            
            return;
        }
        if ([item.identifier isEqualToString:kHomeFeatureReading]) {
                //点读
            [self showAlbumDetailVC:book];
        } else if ([item.identifier isEqualToString:kHomeFeatureDubbing]) {
                //配音
//            SRBookRootModel *bookModel = [[FZMCCacheManager defaultManager] readBookModelFromDocumentWithBookID:book.identifier];
        
            SRBookUnitSelectListViewController *vc = [[SRBookUnitSelectListViewController alloc] init];
            vc.bookID = book.identifier;
//            vc.catalogues = [NSMutableArray arrayWithArray:bookModel.catalogues];
//            vc.groupID = self.groupID;
            vc.startDubbing = YES;
            
            [self pushViewController:vc animated:YES];
        }
    }
}

- (UICollectionViewCell *)cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section >= self.sectionModels.count) {
        return nil;
    }
    
    FZHomeSectionModel *sectionModel = self.sectionModels[indexPath.section];
    NSDictionary *currentCellInfo = [self cellInfo][sectionModel.module];
    FZHomeBaseCollectionViewCell *cell = nil;
    
    NSString *cellIdentifier = currentCellInfo[kHomeCellIdentifierKey];
    if (cellIdentifier) {
        cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
        
        if ([sectionModel.module isEqualToString:kHomeModuleAlbum]) {
            NSArray *books = [FZMCCacheManager defaultManager].books;
            if (indexPath.item == [books count]) {
                    //添加课本按钮
                FZHomeAlbumCollectionViewCell *albumCell = (FZHomeAlbumCollectionViewCell *)cell;
                albumCell.albumMarkHidden = NO;
                albumCell.isAlbum = YES;
                albumCell.indexPath = indexPath;
                albumCell.delegate = nil;
                albumCell.checkButtonHidden = YES;
                
                
                [cell updateCellInfo:self.addCourseModel];
                
            } else {
                FZHomeAlbumCollectionViewCell *albumCell = (FZHomeAlbumCollectionViewCell *)cell;
                albumCell.albumMarkHidden = NO;
                albumCell.isAlbum = YES;
                albumCell.indexPath = indexPath;
                albumCell.delegate = self;
                albumCell.checkButtonHidden = !self.isEditing;
                
                
                SRBaseModel *item = [self itemForIndexPath:indexPath];
                [cell updateCellInfo:item];

            }
        }
        else if ([sectionModel.module isEqualToString:kHomeModuleFeatures]){
            SRHomeFeatureCollectionViewCell *featureCell = (SRHomeFeatureCollectionViewCell *)cell;
            SRBaseModel *item = [self itemForIndexPath:indexPath];

            [featureCell updateCellInfo:item];
        }
        else {
                //课程cell
            if ([cell isKindOfClass:[FZHomeAlbumCollectionViewCell class]]) {
                FZHomeAlbumCollectionViewCell *courseCell = (FZHomeAlbumCollectionViewCell *)cell;
                courseCell.isAlbum = NO;
            }
            SRBaseModel *item = [self itemForIndexPath:indexPath];
            [cell updateCellInfo:item];
        }
        
        
        
    } else {
        cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:kFZHomeBaseCollectionViewCell forIndexPath:indexPath];
    }
    
    if ([cell isKindOfClass:[FZHomeBannerCollectionViewCell class]]) {
        __weak typeof(self) weakSelf = self;
        cell.cellSelectedBlock = ^(UICollectionViewCell *selectedCell, id model) {
            if ([model isKindOfClass:[FZAdvertisementModel class]]) {
                int bannerPage = ((FZHomeBannerCollectionViewCell *)selectedCell).bannerPage;
                
                [MobClick event:@"home_banner" attributes:@{@"clickword":NSStringWith(@"banner%d",bannerPage + 1)}];
                [weakSelf parseSliderModel:model ];
            }
        };
    }
    return cell;
}

- (void)parseSliderModel:(FZAdvertisementModel *)item {
    __weak typeof(self) weakSelf = self;
    if ([item.mainType isEqualToString:kFZHomeBannerTypeAlbum]) {
        
        if (item.identifier && item.identifier > 0) {
                //有专辑id，则直接跳转;
        }
    }else if ([item.mainType isEqualToString:kFZHomeBannerTypeCourse]) {
//        FZDubbingPublicViewController *dubbingPublicVC = [[FZDubbingPublicViewController alloc] init];
//        dubbingPublicVC.courseId = item.identifier;
//        dubbingPublicVC.title = item.title;
//        [self pushViewController:dubbingPublicVC animated:YES];
    } else if ([item.mainType isEqualToString:kFZHomeBannerTypeAdvert]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:item.tintUrlString]];
        
    }else if ([item.mainType isEqualToString:kFZHomeBannerTypeThirdPart]) {
        if (!item.subType) {
            SRCommonWebViewController *commonWebVC = [[SRCommonWebViewController alloc] init];
            commonWebVC.titleStr = item.title;
            commonWebVC.urlString = item.tintUrlString;
            commonWebVC.htmlString = item.html;
            commonWebVC.shareMessage = item.content;
            commonWebVC.shareImageUrl = item.shareImageUrlString;
            commonWebVC.needShare = [item.isShare integerValue];
            [self pushViewController:commonWebVC animated:YES];
        }
    }
    else {//if ([item.mainType isEqualToString:kFZHomeBannerTypeCustom]) {
        
        if (item.tintUrlString && [item.tintUrlString length] > 0) {
            SRCommonWebViewController * commonWebVC=[[SRCommonWebViewController alloc] init];
            commonWebVC.urlString = item.tintUrlString;
            commonWebVC.titleStr= item.title;
            commonWebVC.shareMessage = item.content;
            commonWebVC.shareImageUrl = item.shareImageUrlString;
            commonWebVC.needShare = [item.isShare integerValue];
            [weakSelf pushViewController:commonWebVC animated:YES];
        }
    }
}


- (UICollectionReusableView *)viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    FZHomeSectionModel *sectionModel = [self.sectionModels objectAtIndex:indexPath.section];
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        FZHomeCollectionViewSectionHeaderView *header = [self.collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kFZHomeCollectionViewSectionHeaderView forIndexPath:indexPath];
        header.titleLabel.text = sectionModel.title;
        header.titleLabel.textColor = [FZStyleSheet currentStyleSheet].color_1;
        header.headerModule = sectionModel.module;
        header.indexPath = indexPath;
        header.arrowImageView.hidden = NO;
        header.moreButton.hidden = YES;
        header.iconImageHidden = NO;
        
        __weak typeof(self) weakSelf = self;
        if ([sectionModel.module isEqualToString:kHomeModuleFeatures]) {
//            if (self.isEditing) {
//                [header.moreButton setTitle:@"取消" forState:UIControlStateNormal];
//            } else {
//                [header.moreButton setTitle:@"编辑" forState:UIControlStateNormal];
//            }
            [header.moreButton setTitleColor:[FZStyleSheet currentStyleSheet].color_1 forState:UIControlStateNormal];

            [header.moreButton setTitle:@"切换教材" forState:UIControlStateNormal];
            header.iconImageView.image = [UIImage imageNamed:@"home_choose"];
            
            header.headerSectionActionBlock = ^(NSIndexPath *indexPath, NSString *module) {
                SRMyBookListViewController *vc = [[SRMyBookListViewController alloc] init];
                [weakSelf pushViewController:vc animated:YES];
            };
            
            if (self.bookModel) {
                
                if (self.bookModel.gradeName) {
                    NSString * title = [NSString stringWithFormat:@"%@ •  %@", self.bookModel.gradeName, self.bookModel.title];
                    header.titleLabel.text = title;
                } else {
                    header.titleLabel.text = self.bookModel.title;
                }
                
                
            } else {
                header.titleLabel.text = @"添加课本";
            }
            
            header.headerActionBlock = ^(NSIndexPath *sectionIndexPath, NSString *module) {
                SRMyBookListViewController *vc = [[SRMyBookListViewController alloc] init];
                [weakSelf pushViewController:vc animated:YES];
            };
            
            header.moreButton.hidden = NO;
            header.arrowImageView.hidden = NO;
            
            self.bookHeaderView = header;
        }
        else {
            header.arrowImageView.hidden = YES;
            header.moreButton.hidden = YES;
        }
        
        return header;
    }
    else if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
            FZHomeSectionModel *sectionModel = [self.sectionModels objectAtIndex:indexPath.section];
            
            FZHomeCollectionViewSectionFooterView *footerView = [self.collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:kFZHomeCollectionViewSectionFooterView forIndexPath:indexPath];
            footerView.identifier = [sectionModel.identifier integerValue];
            footerView.module = sectionModel.module;
            footerView.indexPath = indexPath;
            
            footerView.hideContentView = YES;
            return footerView;
    }
    
    return nil;
}


#pragma mark - Event

- (void)onBookHeaderEditButton:(id)sender {
    if (self.isEditing) {
            //完成，退出编辑模式
        [self.bookHeaderView.moreButton setTitle:@"编辑" forState:UIControlStateNormal];
        self.isEditing = NO;
    } else {
            //进入编辑模式
        self.isEditing = YES;
        [self.bookHeaderView.moreButton setTitle:@"取消" forState:UIControlStateNormal];
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(homeViewModel:isEditing:)]) {
        [self.delegate homeViewModel:self isEditing:self.isEditing];
    }
}

-(void)onMoreButtonForSectionModel:(FZHomeSectionModel *)sectionModel {
    
    if ([sectionModel.module isEqualToString:kHomeModuleAlbum]) {
//        [self showMoreCourseListCoureType:MoreCouseTypeAlbum withTitle:sectionModel.title categoryID:sectionModel.identifier];
        SRMyBookListViewController *vc = [[SRMyBookListViewController alloc] init];
        [self pushViewController:vc animated:YES];
        
    } else if ([sectionModel.module isEqualToString:kHomeModuleCourse]) {
//        [self showMoreCourseListCoureType:MoreCouseTypeNormal withTitle:sectionModel.title categoryID:sectionModel.identifier];
    }
}


#pragma mark - Layout Size

- (CGSize)sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    FZHomeSectionModel *sectionModel = self.sectionModels[indexPath.section];
    
    NSDictionary *currentCellInfo = [self cellInfo][sectionModel.module];
    if (currentCellInfo) {
        NSString *sizeString = currentCellInfo[kHomeCellSizeKey];
        CGSize cellSize = CGSizeFromString(sizeString);
        return cellSize;
    }
    
    return CGSizeZero;
}

- (UIEdgeInsets)insetForSectionAtIndex:(NSInteger)section {
    FZHomeSectionModel *sectionModel = self.sectionModels[section];
    if ([sectionModel.module isEqualToString:kHomeModuleSlider]) {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }
    
    return UIEdgeInsetsMake(kFZHomeCollectionViewEdgeSpace, kFZHomeCollectionViewEdgeSpace, kFZHomeCollectionViewEdgeSpace, kFZHomeCollectionViewEdgeSpace);
    
}

- (CGSize)referenceSizeForHeaderInSection:(NSInteger)section {
    FZHomeSectionModel *sectionModel = self.sectionModels[section];
    
    if ([sectionModel.module isEqualToString:kHomeModuleSlider]) {
        return CGSizeZero;
    }
    
    return CGSizeMake(SCREEN_WIDTH, kHomeSectionHeaderHeight);
}

- (CGSize)referenceSizeForFooterInSection:(NSInteger)section  {
    FZHomeSectionModel *sectionModel = self.sectionModels[section];
    
    if ([sectionModel.module isEqualToString:kHomeModuleCourse] && [sectionModel.identifier isEqualToString:kHomeHotVideoSectionID]) {
        return CGSizeMake(SCREEN_WIDTH, kHomeSectionFooterHeight);
    }

    return CGSizeZero;
}

#pragma mark - FZHomeAlbumCollectionViewCellDelegate -

- (void)albumCollectionViewCell:(FZHomeAlbumCollectionViewCell*)cell didSelectItemIndexPath:(NSIndexPath *)indexPath {
    
    self.deleteIndexPath = indexPath;
    FZHomeSectionModel *sectionModel = self.sectionModels[indexPath.section];
    if ([sectionModel.module isEqualToString:kHomeModuleAlbum]) {
        NSArray *books = [FZMCCacheManager defaultManager].books;
        
        WEAKSELF
        if (indexPath.item < [books count]) {
            
            FZHomeCourseModel *item = [books objectAtIndex:indexPath.item];
            NSString *message = [NSString stringWithFormat:@"是否删除 %@", item.title];
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"课程删除"
                                       message:message
                              cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:^{
                
                
                
            }]
                              otherButtonItems:[RIButtonItem itemWithLabel:@"删除" action:^{
                    [[FZMCCacheManager defaultManager] removeBookAtIndex:weakSelf.deleteIndexPath.item];
                
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.collectionView reloadData];
                    });

            }], nil];
            [alertView show];
            
//            [[FZMCCacheManager defaultManager] removeBookAtIndex:indexPath.item];
//            [self.collectionView reloadData];
        }
    }
    
 

}

- (void)albumCollectionViewCell:(FZHomeAlbumCollectionViewCell *)cell deleteItemIndexPath:(NSIndexPath *)indexPath {
    FZHomeSectionModel *sectionModel = self.sectionModels[indexPath.section];
    if ([sectionModel.module isEqualToString:kHomeModuleAlbum]) {
        NSArray *books = [FZMCCacheManager defaultManager].books;
        if (indexPath.item < [books count]) {
            [[FZMCCacheManager defaultManager] removeBookAtIndex:indexPath.item];
            [self.collectionView reloadData];
        }
    }
}

#pragma mark - Private Method

- (NSArray *)itemsForSection:(NSInteger)section {
    FZHomeSectionModel *sectionModel = self.sectionModels[section];
    if ([sectionModel.module isEqualToString:kHomeModuleSlider]) {
        return @[sectionModel];
    } else if ([sectionModel.module isEqualToString:kHomeModuleCourse]) {
        return sectionModel.courses;
    } else if ([sectionModel.module isEqualToString:kHomeModuleAlbum]) {
        NSArray *books = [FZMCCacheManager defaultManager].books;
        return books;
    }
    else if ([sectionModel.module isEqualToString:kHomeModuleFeatures]) {
        return sectionModel.features;
    }
    else {
        return nil;
    }
}


- (NSDictionary *)cellInfo {
    CGFloat commonCellWidth = self.itemSize.width;
    CGFloat commonCellHeight = self.itemSize.height;
    
    return @{
             kHomeModuleSlider: @{kHomeCellIdentifierKey: kFZHomeBannerCollectionViewCell, kHomeCellSizeKey: NSStringFromCGSize(CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH * 175.f/375))},
             kHomeModuleCourse: @{kHomeCellIdentifierKey: kFZHomeAlbumCollectionViewCell, kHomeCellSizeKey: NSStringFromCGSize(CGSizeMake(commonCellWidth , commonCellHeight))},
             kHomeModuleFeatures: @{kHomeCellIdentifierKey: kSRHomeFeatureCollectionViewCell, kHomeCellSizeKey: NSStringFromCGSize(CGSizeMake(commonCellWidth , commonCellHeight))},

             kHomeModuleAlbum: @{kHomeCellIdentifierKey: kFZHomeAlbumCollectionViewCell, kHomeCellSizeKey: NSStringFromCGSize(CGSizeMake(commonCellWidth , commonCellHeight))}};
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if (self.delegate && [self.delegate respondsToSelector:@selector(homeViewModel:pushViewController:)]){
        [self.delegate homeViewModel:self pushViewController:viewController];
    }
}

- (void)onAddAlbumButton {
    SRGradeListViewController *vc = [[SRGradeListViewController alloc] init];
    [self pushViewController:vc animated:YES];
}

- (void)showAlbumDetailVC:(FZHomeCourseModel *)item {
    
        //若课本信息已经下载则显示，若没有则提示重新下载
    if ( [[FZMCCacheManager defaultManager] isExistBookFile:item]){
        SRLearnAlbumViewController *vc = [[SRLearnAlbumViewController alloc] init];
        vc.bookID = [NSString stringWithFormat:@"%@", item.identifier];
        [self pushViewController:vc animated:YES];
    } else {
            //没有下载文件信息，提示删除再次下载
        if (self.delegate && [self.delegate respondsToSelector:@selector(homeViewModel:showMessage:)]){
            [self.delegate homeViewModel:self showMessage:@"还没有下载该教材，请重新添加下载"];
        }
    }

}

@end
